package uk.co.richardwkirk.parkrun.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import uk.co.richardwkirk.parkrun.data.ParkrunDataLoadException;

public class ParkrunPageLoader {

	/**
	 * Load file of results to be converted into a set of runners.
	 * 
	 * @param file
	 * @return
	 * @throws ParkrunDataLoadException 
	 */
	private InputStreamReader loadFromClasspath(String filename) throws ParkrunDataLoadException
	{
		// Open the file to input
		InputStream is = ParkrunPageLoader.class.getResourceAsStream(filename);
		InputStreamReader isr = new InputStreamReader(is);
		return isr;
	}
	
	
	private InputStreamReader loadFromWeb(String resourceAddress) throws ParkrunDataLoadException {
		try {
			ParkrunWebConnection webConnection = new ParkrunWebConnection();
			return webConnection.loadStreamReader(resourceAddress);
		} catch (ParkrunWebException e) {
			throw new ParkrunDataLoadException("Could not load results from parkrun site.", e);
		}
	}
	

	public String load(String resourceAddress) throws ParkrunDataLoadException {
		InputStreamReader isr = loadStreamReader(resourceAddress);
		return getPageContent(isr);
	}
	
	
	public InputStreamReader loadStreamReader(String resourceAddress) throws ParkrunDataLoadException {
		//System.out.println("Loading parkrun data from [" + resourceAddress + "]");
		if (resourceAddress.contains("classpath")) {
			return loadFromClasspath(getFilenameFromClasspath(resourceAddress));
		}
		else {
			return loadFromWeb(resourceAddress);
		}
	}

	
	private String getPageContent(InputStreamReader inputStreamReader) throws ParkrunDataLoadException {
		// Read the page into a string
		try {
			StringBuilder buf = new StringBuilder();
			while (true) {
				int ch = inputStreamReader.read();
				if (ch < 0) {
					break;
				}
				buf.append((char) ch);
			}
			return buf.toString();
		}
		catch (IOException e) {
			throw new ParkrunDataLoadException("Could not read content from connection to parkrun website.", e);
		}
	}


	private String getFilenameFromClasspath(String resourceAddress) {
		String[] addressParts = resourceAddress.split(":");
		if (addressParts.length > 0) {
			return addressParts[1];
		}
		else {
			return resourceAddress;
		}
	}

	
}
